/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable no-restricted-globals */
import React, { useEffect, useState, useRef } from 'react';
import { Modal, Form, InputNumber, Radio, Row, Col, message, Icon, Button } from 'antd';
import { connect } from 'dva';
import Qrcode from '@/components/KbQrcode';
import { getChargingResult } from '@/services/area';
import {} from './style.less';

const { Item: FormItem } = Form;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const limitDecimals = value => {
  if (typeof value === 'string') {
    return !isNaN(Number(value)) ? value.replace(/^(0+)|[^\d]/g, '') : 1;
  }
  if (typeof value === 'number') {
    return !isNaN(value) ? String(value).replace(/^(0+)|[^\d]/g, '') : 1;
  }
  return 0;
};

const formMassageMap = {
  sms: ' 条/每个驿站（单次最高10000条）',
  money: ' 元/每个驿站（单次最高500元）',
};

const payStatusMap = {
  0: 'loading',
  1: 'success',
  2: 'failed',
};

const QrcodePay = ({
  reStart = () => {},
  money,
  order_number,
  count,
  qrCodeUrl,
  chargingType,
  postCount,
}) => {
  const [payResult, setPayResult] = useState({});

  const success = payStatusMap[payResult.status] === 'success';
  const failed = payStatusMap[payResult.status] === 'failed';
  const smsPay = chargingType === 'sms';

  const orderNum = useRef('');

  useEffect(
    () => {
      orderNum.current = order_number;
    },
    [order_number],
  );

  const getScanResult = stopLoop => {
    getChargingResult({ order_number: orderNum.current }).then(res => {
      const { code, data, msg } = res;
      const { status } = data || {};
      if (['1', '2'].includes(status)) {
        stopLoop();
        setPayResult({
          status,
          finished: true,
        });
      }
      if (code != 0) {
        stopLoop();
        setPayResult({});
        message.warning(msg);
      }
    });
  };

  // 重新扫码
  const onReStart = () => {
    setPayResult({});
    reStart(chargingType, smsPay ? count : money);
  };

  return (
    <>
      {payResult.finished ? (
        <Row type="flex" justify="center" gutter={[10, 10]} style={{ textAlign: 'center' }}>
          <Col
            span={24}
            style={{
              fontSize: 32,
              color: success ? 'green' : '#ffcc02',
              textAlign: 'center',
            }}
          >
            <Icon type={success ? 'check' : 'exclamation-circle'} />
          </Col>
          <Col span={24}>{success ? '充值成功！' : '充值失败'}</Col>
          <Col span={24}>{success && '如需开票，请一周内联系客服'}</Col>
          <Col span={24}>{failed && '如已扣款，请联系总部管理员'}</Col>
          <Col span={24}>{failed && <a onClick={onReStart}>重新扫码</a>}</Col>
        </Row>
      ) : (
        <Row type="flex" justify="center" gutter={[10, 10]} style={{ textAlign: 'center' }}>
          <Col span={24}>
            共计
            {(smsPay ? count : postCount) || 1}
            {smsPay ? '条短信' : '个驿站'}， 需付款
            <span style={{ color: 'red' }}>{money || 0}元</span>
          </Col>
          <Col span={24}>
            <Qrcode
              qrcodeExpiredTime={0.5}
              src={qrCodeUrl}
              getScan={stopLoop => getScanResult(stopLoop)}
            />
          </Col>
          <Col span={24}>请使用支付宝扫码付款</Col>
        </Row>
      )}
    </>
  );
};

const ChargePostModal = connect(({ loading, area }) => ({
  chargingType: area.chargingType, // sms，money
  loading: loading.effects['global/getYzList'],
  charging: loading.effects['area/charging'],
}))(
  Form.create({
    onValuesChange(props, values) {
      const { dispatch, form } = props;
      const { type } = values;
      if (type) {
        form.resetFields();
        dispatch({
          type: 'area/save',
          payload: {
            chargingType: type,
          },
        });
      }
    },
  })(props => {
    const {
      visible,
      charging,
      onCancel,
      onOk,
      form,
      chargingType,
      selectedRows,
      dispatch,
      payInfo,
      refreshPage = () => {},
    } = props;
    const { getFieldDecorator, validateFields, resetFields } = form;

    const onSubmit = (type, money) => {
      validateFields((err, value) => {
        if (err) return;
        let formValue = { ...value };
        if (type && money) {
          formValue = { type, money };
        }
        onOk && onOk(formValue);
      });
    };

    const cancel = () => {
      resetFields();
      if (payInfo.order_number) {
        refreshPage();
      }
      onCancel && onCancel();
    };

    useEffect(
      () => {
        // 防止单位显示错误
        !visible &&
          dispatch({
            type: 'area/save',
            payload: {
              chargingType: 'sms',
            },
          });
      },
      [visible, dispatch],
    );

    return (
      <Modal
        centered
        visible={visible}
        destroyOnClose
        confirmLoading={charging}
        title="为下级驿站充值"
        onCancel={cancel}
        footer={
          payInfo.order_number ? null : (
            <Button type="primary" onClick={() => onSubmit()}>
              确认充值
            </Button>
          )
        }
      >
        {payInfo.order_number ? (
          <QrcodePay
            reStart={(type, amount) => onSubmit(type, amount)}
            money={payInfo.money}
            order_number={payInfo.order_number}
            count={payInfo.count}
            qrCodeUrl={payInfo.qrCodeUrl}
            chargingType={payInfo.chargingType}
            postCount={selectedRows.length}
          />
        ) : (
          <Form {...formItemLayout}>
            <FormItem label="充值类型">
              {getFieldDecorator('type', {
                initialValue: 'sms',
              })(
                <Radio.Group>
                  <Radio value="sms">充短信</Radio>
                  <Radio value="money">充可消费金额</Radio>
                </Radio.Group>,
              )}
            </FormItem>
            <FormItem label="站点数量">
              <span>{selectedRows.length || 1}</span>
            </FormItem>
            <FormItem label={`充值${chargingType === 'sms' ? '条数' : '金额'}`}>
              {getFieldDecorator('money', {
                initialValue: 1,
                rules: [
                  {
                    required: true,
                    message: '请填写充值数量',
                  },
                  {
                    validator: (rule, value, callback) => {
                      const max = chargingType == 'sms' ? 10000 : 500;
                      const info =
                        chargingType == 'sms'
                          ? '每个驿站每次最多充值10000条'
                          : '每个驿站每次最多充值500元';
                      if (value > max) {
                        callback(info);
                        return;
                      }
                      callback();
                    },
                  },
                ],
              })(<InputNumber min={1} step={100} formatter={limitDecimals} />)}
              <span>{formMassageMap[chargingType]}</span>
            </FormItem>
          </Form>
        )}
      </Modal>
    );
  }),
);

export default ChargePostModal;
